import { app, BrowserWindow, clipboard, desktopCapturer, dialog, globalShortcut, ipcMain, nativeImage, screen } from 'electron';
import * as fs from 'fs';
import * as path from 'path';

let mainWindow: BrowserWindow;
let screenshotWindow: BrowserWindow | null = null;

function createWindow(): void {
  // 创建主窗口
  mainWindow = new BrowserWindow({
    height: 600,
    width: 800,
    minHeight: 400,
    minWidth: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js'),
    },
    icon: path.join(__dirname, '../assets/icon.png'), // 可选：添加应用图标
    titleBarStyle: 'default',
    show: false,
  });

  // 加载应用
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:3000');
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(path.join(__dirname, 'index.html'));
  }

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  mainWindow.on('closed', () => {
    app.quit();
  });
}

// 创建截图选择窗口
function createScreenshotWindow(): void {
  // 如果已经有截图窗口，先关闭它
  if (screenshotWindow && !screenshotWindow.isDestroyed()) {
    screenshotWindow.close();
    screenshotWindow = null;
  }

  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  
  screenshotWindow = new BrowserWindow({
    width,
    height,
    x: 0,
    y: 0,
    frame: false,
    transparent: true,
    alwaysOnTop: true,
    fullscreen: true,
    skipTaskbar: true, // 不在任务栏显示
    resizable: false,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  if (process.env.NODE_ENV === 'development') {
    screenshotWindow.loadURL('http://localhost:3000/#/screenshot');
  } else {
    screenshotWindow.loadFile(path.join(__dirname, 'index.html'), { hash: 'screenshot' });
  }

  screenshotWindow.on('closed', () => {
    screenshotWindow = null;
    // 清空存储的截图数据
    currentScreenshotData = null;
  });

  // 窗口加载完成后确保获得焦点
  screenshotWindow.once('ready-to-show', () => {
    if (screenshotWindow && !screenshotWindow.isDestroyed()) {
      screenshotWindow.show();
      screenshotWindow.focus();
      screenshotWindow.setAlwaysOnTop(true, 'screen-saver');
    }
  });
}

// 应用准备就绪
app.whenReady().then(() => {
  createWindow();

  // 注册全局快捷键进行截图
  registerScreenshotShortcut(currentShortcut);

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('will-quit', () => {
  // 取消注册所有快捷键
  globalShortcut.unregisterAll();
});

// IPC 事件处理
ipcMain.handle('capture-screen', async () => {
  return await captureScreen();
});

ipcMain.handle('save-screenshot', async (event, dataURL: string, filename?: string) => {
  return await saveScreenshot(dataURL, filename);
});

ipcMain.handle('copy-to-clipboard', async (event, dataURL: string) => {
  return await copyToClipboard(dataURL);
});



ipcMain.handle('close-screenshot-window', () => {
  if (screenshotWindow) {
    screenshotWindow.close();
    screenshotWindow = null;
  }
  // 清空存储的截图数据
  currentScreenshotData = null;
});

ipcMain.handle('minimize-main-window', () => {
  if (mainWindow) {
    mainWindow.minimize();
  }
});

ipcMain.handle('get-sources', async () => {
  try {
    // 获取高质量的屏幕截图
    const primaryDisplay = screen.getPrimaryDisplay();
    const { width, height } = primaryDisplay.size;
    const scaleFactor = primaryDisplay.scaleFactor || 1;
    
    const sources = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: { 
        width: Math.floor(width * scaleFactor * 2), // 使用更高的分辨率
        height: Math.floor(height * scaleFactor * 2) 
      },
      fetchWindowIcons: false
    });
    return sources;
  } catch (error) {
    console.error('Error getting sources:', error);
    return [];
  }
});

// 存储当前的屏幕截图数据
let currentScreenshotData: string | null = null;

ipcMain.handle('get-current-screenshot', async () => {
  return currentScreenshotData;
});

// 存储用户设置的截图路径
let customSavePath: string | null = null;

// 存储用户设置的快捷键
let currentShortcut: string = 'CommandOrControl+Shift+A';

ipcMain.handle('select-save-folder', async () => {
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      properties: ['openDirectory'],
      title: '选择截图保存位置',
      message: '选择要保存截图的文件夹'
    });
    
    if (!result.canceled && result.filePaths.length > 0) {
      customSavePath = result.filePaths[0];
      return customSavePath;
    }
    
    return null;
  } catch (error) {
    console.error('选择文件夹失败:', error);
    return null;
  }
});

ipcMain.handle('get-save-folder', async () => {
  return customSavePath || app.getPath('downloads');
});

ipcMain.handle('reset-save-folder', async () => {
  customSavePath = null;
  return app.getPath('downloads');
});

// 快捷键管理
function registerScreenshotShortcut(shortcut: string): boolean {
  try {
    // 先取消注册现有的快捷键
    globalShortcut.unregisterAll();
    
    // 注册新的快捷键
    const success = globalShortcut.register(shortcut, () => {
      captureScreen();
    });
    
    if (success) {
      currentShortcut = shortcut;
      console.log(`快捷键注册成功: ${shortcut}`);
    } else {
      console.log(`快捷键注册失败: ${shortcut}`);
    }
    
    return success;
  } catch (error) {
    console.error('注册快捷键时出错:', error);
    return false;
  }
}

ipcMain.handle('set-shortcut', async (event, shortcut: string) => {
  try {
    const success = registerScreenshotShortcut(shortcut);
    
    // 如果设置成功，通知所有窗口快捷键已更改
    if (success && mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('shortcut-changed', shortcut);
    }
    
    return { success, message: success ? '快捷键设置成功' : '快捷键注册失败，可能与其他应用冲突' };
  } catch (error) {
    return { success: false, message: '设置快捷键时出错' };
  }
});

ipcMain.handle('get-shortcut', async () => {
  return currentShortcut;
});

ipcMain.handle('reset-shortcut', async () => {
  const defaultShortcut = 'CommandOrControl+Shift+A';
  const success = registerScreenshotShortcut(defaultShortcut);
  
  // 如果重置成功，通知所有窗口快捷键已更改
  if (success && mainWindow && !mainWindow.isDestroyed()) {
    mainWindow.webContents.send('shortcut-changed', defaultShortcut);
  }
  
  return { 
    success, 
    shortcut: success ? defaultShortcut : currentShortcut,
    message: success ? '快捷键已重置为默认' : '重置失败'
  };
});

ipcMain.handle('validate-shortcut', async (event, shortcut: string) => {
  try {
    // 检查快捷键是否为空
    if (!shortcut || shortcut.trim() === '') {
      return { valid: false, message: '快捷键不能为空' };
    }
    
    // 检查快捷键格式是否有效（支持更多字符和功能键）
    const validKeyPattern = /^(CommandOrControl|Command|Control|Alt|Shift)(\+(CommandOrControl|Command|Control|Alt|Shift|[A-Za-z0-9]|F[1-9]|F1[0-2]|Space|Enter|Escape|Tab|Backspace|Delete|Home|End|PageUp|PageDown|Up|Down|Left|Right|Insert))+$|^[A-Za-z0-9]$|^F[1-9]$|^F1[0-2]$/;
    
    if (!validKeyPattern.test(shortcut)) {
      return { valid: false, message: '快捷键格式无效，请使用有效的组合键' };
    }
    
    // 检查是否包含修饰键（推荐使用组合键）
    const hasModifier = /^(CommandOrControl|Command|Control|Alt|Shift)/.test(shortcut);
    if (!hasModifier) {
      return { valid: false, message: '建议使用包含修饰键的组合键（Ctrl/Cmd + 其他键）' };
    }
    
    // 检查是否与当前快捷键相同
    if (shortcut === currentShortcut) {
      return { valid: true, message: '当前快捷键' };
    }
    
    // 尝试临时注册以检查是否可用
    try {
      const isAvailable = globalShortcut.register(shortcut, () => {});
      if (isAvailable) {
        globalShortcut.unregister(shortcut);
        return { valid: true, message: '快捷键可用' };
      } else {
        return { valid: false, message: '快捷键已被其他应用占用' };
      }
    } catch (regError) {
      return { valid: false, message: '快捷键格式不被系统支持' };
    }
  } catch (error) {
    console.error('快捷键验证错误:', error);
    return { valid: false, message: '快捷键验证失败' };
  }
});

// 通知主窗口截图已保存
ipcMain.handle('notify-screenshot-saved', async (event, screenshotInfo: { filename: string; dataURL: string; savedPath: string }) => {
  try {
    if (mainWindow && !mainWindow.isDestroyed()) {
      // 发送事件给主窗口
      mainWindow.webContents.send('screenshot-saved', screenshotInfo);
      return true;
    }
    return false;
  } catch (error) {
    console.error('通知截图保存失败:', error);
    return false;
  }
});

// 截图功能
async function captureScreen(): Promise<string[]> {
  try {
    // 防止重复调用：如果截图窗口已经存在，直接返回
    if (screenshotWindow && !screenshotWindow.isDestroyed()) {
      console.log('截图窗口已存在，忽略重复调用');
      screenshotWindow.focus(); // 确保现有窗口获得焦点
      return [];
    }

    // 最小化主窗口
    if (mainWindow && !mainWindow.isMinimized()) {
      mainWindow.minimize();
    }

    // 等待一下确保窗口最小化完成
    await new Promise(resolve => setTimeout(resolve, 500));

    // 获取主显示器的实际分辨率
    const primaryDisplay = screen.getPrimaryDisplay();
    const { width, height } = primaryDisplay.size;
    const scaleFactor = primaryDisplay.scaleFactor || 1;
    
    const sources = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: { 
        width: Math.floor(width * scaleFactor), 
        height: Math.floor(height * scaleFactor) 
      },
      fetchWindowIcons: false
    });

    if (sources.length > 0) {
      // 存储屏幕截图数据，使用最高质量
      const primaryScreenSource = sources.find(source => source.id.startsWith('screen:')) || sources[0];
      currentScreenshotData = primaryScreenSource.thumbnail.toDataURL();
      
      // 创建截图选择窗口
      createScreenshotWindow();
      
      // 确保截图窗口获得焦点和键盘事件
      if (screenshotWindow) {
        screenshotWindow.focus();
        screenshotWindow.setAlwaysOnTop(true, 'screen-saver');
      }
      
      // 返回高质量截图数据URLs
      return sources.map(source => source.thumbnail.toDataURL());
    }
    
    return [];
  } catch (error) {
    console.error('截图失败:', error);
    return [];
  }
}



// 保存截图
async function saveScreenshot(dataURL: string, filename?: string): Promise<string> {
  try {
    const base64Data = dataURL.replace(/^data:image\/png;base64,/, '');
    const buffer = Buffer.from(base64Data, 'base64');
    
    const defaultFilename = filename || `screenshot-${Date.now()}.png`;
    // 使用用户设置的路径或默认下载路径
    const savePath = customSavePath || app.getPath('downloads');
    const filePath = path.join(savePath, defaultFilename);
    
    fs.writeFileSync(filePath, buffer);
    
    return filePath;
  } catch (error) {
    console.error('保存截图失败:', error);
    throw error;
  }
}

// 复制截图到剪贴板
async function copyToClipboard(dataURL: string): Promise<boolean> {
  try {
    // 将 data URL 转换为 NativeImage
    const image = nativeImage.createFromDataURL(dataURL);
    
    // 复制到剪贴板
    clipboard.writeImage(image);
    
    return true;
  } catch (error) {
    console.error('复制到剪贴板失败:', error);
    return false;
  }
}